<?php

	require_once("src/model/ValidateLoginInfo.php");	
	require_once("src/view/LoginForm.php");	
	

class CheckLoginForm
{				
	public function CheckIfSubmitted() //TODO: FÖR LÅNG METOD.
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST') 
		{
			$validateLoginInfo = new ValidateLoginInfo();
			$getPosts = new LoginForm();
			
			$username = $getPosts->getUsername();
			$userPassword = $getPosts->getUserPassword();
			$sessionLogin = $this->GetLoginSession();
			

		
		    if(!empty($username) && !empty($userPassword)&& $sessionLogin === false)
		    {  
				$loggedIn = $validateLoginInfo->LoginValidation( 
				$username , $userPassword);					  												
				
				if($loggedIn === false)
				{	
					$this->SetMessageSession("Felaktigt användarnamn och/eller lösenord.");
					$this->SetLastEnteredUsernameSession($username); 
				}
				elseif($loggedIn === true)
				{
					$this->SetLastEnteredUsernameSession($username);
					
					$this->SetLoginSession(true);
					
					// cookies. 
					if($getPosts->RememberMe())
					{
						setcookie("username", $username, time()+60*60*24*30);
						setcookie("userpassword", md5($userPassword), time()+60*60*24*30);
						$this->SetMessageSession('Du har loggat in, och vi kommer ihåg dig nästa gång.');
					}
					else 
					{
						$this->SetMessageSession('Du har loggat in.');	
					}
				}
		    }			
			// NO PASSWORD.
			elseif(!empty($username) && empty($userPassword))
			{
				$this->SetMessageSession("Lösenord saknas");
				$this->SetLastEnteredUsernameSession($username);
			}
			// NO USERNAME / NO USERNAME AND PASSWORD
			elseif(empty($username) && empty($userPassword) 
			    || empty($username) && !empty($userPassword)) 
			{
				$this->SetMessageSession("Användarnamn saknas.");
				$this->SetLastEnteredUsernameSession("");
			}
			
		}	 
	}
	
	/**
	 * @return bool
	 */
	public function GetLoginSession()
	{
		if(isset($_SESSION['loggedIn']))
		{
			return $_SESSION['loggedIn'];
		}
		else return FALSE;
	}
	/**
	 * @return string
	 */
	public function GetLastEnteredUsernameSession()
	{
		if(isset($_SESSION['lastEnteredUsername']))
		{
			return htmlspecialchars($_SESSION['lastEnteredUsername']);
		}
		else
		{
			return "";
		} 
		
	}
	/**
	 * @return string
	 */
	public function GetMessageSession()
	{
		if(isset($_SESSION['message']))
		{
			return htmlspecialchars($_SESSION['message']);
		}
		else
		{
			return "";
		} 
	}
	
	
	/**
	 * $loginBool, boolean,
	 */
	public function SetLoginSession($loginBool)
	{
		$_SESSION['loggedIn'] = $loginBool;
	}
	
	/**
	 * $lastEnteredUsername, string
	 */
	public function SetLastEnteredUsernameSession($lastEnteredUsername)
	{
		$_SESSION['lastEnteredUsername'] = $lastEnteredUsername;
	}
	
	/**
	 * $message, string
	 */
	public function SetMessageSession($message)
	{
		$_SESSION['message'] = $message;
	}
	
	
	
	
}
